import 'package:flutter/material.dart';
import 'shop.dart';
import 'Util.dart';
import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
import 'dart:async';
import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
class ReasonPage extends StatefulWidget {
  ReasonPage({Key key, this.title,this.para}) : super(key: key);
  final String title;
  final Map<String,dynamic> para;
  @override
  _ReasonPage createState() => _ReasonPage();
}

class _ReasonPage extends State<ReasonPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }
  List<Map<String,dynamic>> types = [];
  loadData() {
    SharedPreferences.getInstance().then((value){
      setState(() {
        String domain = value.getString("buildings").toMap()["subdomain"].toString();
        print(domain);
        var dic = widget.para;
        dic["api_key"] = "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA";
        dic["lang"] = "en";
        print(dic);
        var dio = Dio();
        if (ShareHandle.instance.proxy.length > 0){
          (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
            client.findProxy = (uri) {
              return ShareHandle.instance.proxy;
            };
          };
        }
        dio.post("${domain}/api/visitor/reason",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          if (result.item2){
            setState(() {
              this.types = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
      });
    });
  }
  var name = "";
  int sex = 0;
  List<List<String>> keys = [["探訪","送貨","外賣"],["補習","教琴","家助"],["維修","裝修","其他"],];
  List<List<bool>> values = [[false,false,false],[false,false,false],[false,false,false],];
  @override
  Widget build(BuildContext context) {
    keys = [];
    values = [];
    int i = 0;
    for (final x in this.types){
      if (i % 3 == 0){
        keys.add([x["name"]]);
        values.add([false]);
      }else{
        keys.last.add(x["name"]);
        values.last.add(false);
      }
      i++;
    }
    List<Widget> widgets = [];
    for (int i = 0; i < values.length; i++) {
      List<Widget> rows= [];
      for (int j = 0; j < values[i].length; j++){
        var row = Row(children: <Widget>[
          Checkbox(value: values[i][j],onChanged: (v){
            setState(() {
              values[i][j] = v;
            });
          },),
          Text(keys[i][j],style: TextStyle(fontWeight: FontWeight.bold))
        ],);
        rows.add(Expanded(child: row,));
      }
      widgets.add(Row(children: rows,));
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(padding: EdgeInsets.all(20),child: Column(
        children: <Widget>[
          Text("請選擇到訪原因",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 21)),
          SizedBox(
            height: 20,
          ),
          Row(
            children: <Widget>[
              Padding(child: Text("到訪原因",style: TextStyle(fontWeight: FontWeight.bold)),padding: EdgeInsets.all(20),),
              Expanded(child: Column(children: widgets,),),
            ],
          ),
          Row(children: <Widget>[
            Align(alignment: Alignment.centerLeft,child: MaterialButton(
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              height: 40,
              minWidth: 100,
              padding: EdgeInsets.all(0),
              color: Color(0xff4a701e),
              textColor: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.all(Radius.circular(20))),
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("上一步"),
            ),)
            ,Align(alignment: Alignment.centerLeft,child: MaterialButton(
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              height: 40,
              minWidth: 100,
              padding: EdgeInsets.all(0),
              color: Color(0xff4a701e),
              textColor: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.all(Radius.circular(20))),
              onPressed: () {
                var dic = this.widget.para;
                List<int> ids = [];
                for(var i = 0;i<3;i++){
                  for(var j = 0;j<3;j++){
                    if(values[i][j]){
                      ids.add(i*3+j+1);
                    }
                  }
                }
                dic["visit_reason"] = ids.toString();
                Navigator.push( context, MaterialPageRoute(builder: (context) => ShopPage(title: widget.title,para: dic)),);
              },
              child: Text("下一步"),
            ),),
          ],),
        ],
      ),),
    );
  }
}